﻿namespace PAR.Audio
{
    using System;
    using System.IO.IsolatedStorage;
    using NAudio.Wave;

    public class AudioGraph : IDisposable
    {
        private AudioCapture capture;
        private readonly SampleAggregator aggregator;

        public event EventHandler<MaxSampleEventArgs> MaximumCalculated
        {
            add { aggregator.MaximumCalculated += value; }
            remove { aggregator.MaximumCalculated -= value; }
        }

        public event EventHandler<FftEventArgs> FftCalculated
        {
            add { aggregator.FftCalculated += value; }
            remove { aggregator.FftCalculated -= value; }
        }

        public AudioGraph()
        {
            capture = new AudioCapture();
            capture.OnSample += OnSample;

            aggregator = new SampleAggregator { NotificationCount = 200, PerformFFT = true };
        }

        void OnSample(object sender, SampleEventArgs e)
        {
            aggregator.Add(e.Left);
        }

        public void Stop(string filename)
        {
            var file = IsolatedStorageFile.GetUserStoreForApplication();
            var stream = file.CreateFile(filename);
            capture.Stop(stream);
            stream.Close();
        }

        public void Start()
        {
            aggregator.NotificationCount = 200;
            capture.Start(new WaveFormat(8000, 1));
        }

        public void Dispose()
        {
            if (capture != null)
            {
                capture.OnSample -= OnSample;
                capture.Dispose();
                capture = null;
            }
        }
    }
}
